package com.dengqi.mymodule.tools;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.widget.Toast;

import java.io.File;
import java.util.Iterator;
import java.util.List;

import androidx.core.content.FileProvider;

/**
 * 7.0uri需要读写权限
 * 文件转uri需要：
 * uri = FileProvider.getUriForFile(context, AUTHORITIES, file);
 * 授权(安装apk时需要)：
 * intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
 * 授权(系统相册、相机、裁剪时需要)：
 * context.grantUriPermission(packageName, saveUri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
 * 参考：https://blog.csdn.net/fesdgasdgasdg/article/details/73441062
 */
public class UriUtils {

    /**
     * 写入uri
     * 申请写入uri权限
     * @param context
     * @param intent
     * @param targetUri
     */
    public static boolean applyUri(Context context, Intent intent, Uri targetUri) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            List resInfoList = context.getApplicationContext().getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
            if (resInfoList.size() == 0) {
                Toast.makeText(context.getApplicationContext(), "没有合适的应用程序", Toast.LENGTH_SHORT).show();
                return false;
            }
            Iterator resInfoIterator = resInfoList.iterator();
            while (resInfoIterator.hasNext()) {
                ResolveInfo resolveInfo = (ResolveInfo) resInfoIterator.next();
                String packageName = resolveInfo.activityInfo.packageName;
                context.getApplicationContext().grantUriPermission(packageName, targetUri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            }
        }
        return true;
    }

    /**
     * file to uri
     * 读取uri
     * 权限intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
     * 7.0开始不能直接访问原路径
     */
    public static Uri file2Uri(Context context, File file) {
        Uri sourceUri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            // 适配android7.0 ，不能直接访问原路径
            sourceUri = FileProvider.getUriForFile(context.getApplicationContext(), "com.dengqi.mymodule.fileprovider", file);
        } else {
            sourceUri = Uri.fromFile(file);
        }
        return sourceUri;
    }

    /**
     * bitmap to uri
     */
    public static Uri bitmap2Uri(Context context, Bitmap bitmap) {
        return Uri.parse(MediaStore.Images.Media.insertImage(context.getApplicationContext().getContentResolver(), bitmap, null, null));
    }

}